<?php

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.view');

class ApkipasViewDetail extends JView{
	
	protected $item = null;

	function display($tpl = null) {
	
		$this->setModel($this->getModel(), true);
		$fnc = 'display'.ucfirst($this->getLayout());
		if (is_callable(array(&$this, $fnc)))
			$this->$fnc($tpl);
		else
			parent::display($tpl);
	}
	
	function displayDefault($tpl = null){
		
		// Initialise variables
		$item = $this->get('Data');
		$user = JFactory::getUser();
		$download 	= ApkipasHelper::getDownload($item->product_id);
		// Check for errors.
		if (count($errors = $this->get('Errors'))) {
			JError::raiseWarning(500, implode("\n", $errors));
			return false;
		}

		if ($item === false) {
			return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
		}	
		
		$app = JFactory::getApplication('site');
		$params =  & $app->getParams('com_apkipas');
		$tags = $this->getTags($item->itune_id);
		
		
		$category_related = $this->getRelatedItem($item->category,$item->title_id);
		$seller_related = $this->getRelatedItem($item->seller,$item->title_id);
		$tag_related = $this->getRelatedItembyTag($tags, $item->category, $item->seller,$item->title_id);
		$this->updateHit($item->title_id);
		
		$this->_prepareDocument($params,$item);
		$this->assignRef('params', $params);
		$this->assignRef('item',$item);
		$this->assignRef('tags',$tags);
		$this->assignRef('download',$download);
		$this->assignRef('user',$user);
		$this->assignRef('tag_related',$tag_related);
		$this->assignRef('category_related',$category_related);
		$this->assignRef('seller_related',$seller_related);
		
		parent::display($tpl);
	}
	
	function displayTag($tpl = null){
		// Initialise variables
		$items		= $this->get('Tags');
		$tag = JRequest::getVar('tag');
		$tag = str_ireplace(':', '-', $tag);
		// Check for errors.
		if (count($errors = $this->get('Errors'))) {
			JError::raiseWarning(500, implode("\n", $errors));
			return false;
		}
	
		if ($items === false) {
			return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
		}
	
		$app = JFactory::getApplication('site');
		$params =  & $app->getParams('com_apkipas');
	
		jimport('joomla.html.pagination');
		$limitstart = JRequest::getVar('limitstart');
		$pagination = new JPagination(10000, $limitstart, 10);
	
		$this->_prepareTagDocument($params,$tag);
		$this->assignRef('params', $params);
		$this->assignRef('items', $items);
		$this->assignRef('pagination', $pagination);
		parent::display($tpl);
	}

	protected function _prepareDocument($params,$item)
	{
		$document = &JFactory::getDocument();
		$document->setTitle($item->main_title.' ipa. iPhone | iPad | iPod touch apps & games for download');
		
		$metaDescItem = preg_replace("#{(.*?)}(.*?){/(.*?)}#s", '', $item->des);
		$metaDescItem = ApkipasHelper::characterLimit($item->des);
		$metaDescItem .= ' All iphone, ipad, ipod touch, ipa games for download';
		
		if($metaDescItem != '')
		{
			$document->setDescription($metaDescItem);
		}

		$tag = explode(' ', $item->title);
		$tag[] = $item->category;
		$tag[] = $item->seller;
		$meta_keywords = implode(', ',$tag);
		
		$document->setMetadata('keywords', $meta_keywords);
	}
	
	protected function _prepareTagDocument($params,$tag)
	{
		$document = &JFactory::getDocument();
		$app = JFactory::getApplication('site');
		$document->setTitle($tag.' ipa. iPhone | iPad | iPod touch apps & games for download');

		$document->setMetadata('keywords', $tag.', iPhone, iPad, iPod, iPod touch, apps, ipa, download, games, version, Angry Birds, Lifestyle, Books, Travel, Sports, Utilities');
		
	}
	
	function getTags($id,$type = 0){
		$db = &JFactory::getDbo();
		$query = 'SELECT b.*,a.id as itune_id FROM #__apkipas_refs as a
					LEFT JOIN #__apkipas_tags as b ON a.tagid = b.id 
					where a.id = '.$id;
		$db->setQuery($query);
		return $db->loadObjectList();
	}
	
	function updateHit($id){
		$db = &JFactory::getDbo();
		$obj = new stdClass();
		$obj->id = $id;
		$obj->hit = 1;
		$obj->date = time();
		$obj->date_full = date('Y-m-d') ;
		$db->insertObject('#__apkipas_hits', $obj);
	}
	
	function getRelatedItem($key,$id){
		$db = JFactory::getDbo();

		$query = 'SELECT id FROM #__apkipas_refs where tagid = (SELECT id from apkipas_apkipas_tags where text = "'.$key.'")  ORDER BY RAND() LIMIT 20 ';
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		if(count($rs) > 0){
			foreach ($rs as $item)
				$itune_id[] = $item->id;
			$query = 'SELECT a.id as title_id , a.title as main_title, a.alias, b.des ,b.bg 
			FROM #__apkipas_titles as a
			LEFT JOIN #__apkipas_resources as b ON a.product_id = b.id 
			WHERE b.itune_id IN ('.implode(',', $itune_id).') AND a.id != '.$id.' GROUP BY b.itune_id ORDER BY a.id DESC LIMIT 6';
			
			$db->setQuery($query);
			return $db->loadObjectList();
		}
		
	}
	
	function getRelatedItembyTag($tags,$category,$seller,$id){
		$db = JFactory::getDbo();
		$arr = array();
		foreach ($tags as $tag){
			$category = JApplication::stringURLSafe($category);
			$seller = JApplication::stringURLSafe($category);
			if($tag->text != $category && $tag->text != $seller){
				$arr[] = $tag->id;
			}
				
		}
		
		if(count($arr) > 0)
			$query = 'SELECT id FROM #__apkipas_refs where tagid IN ('.implode(',', $arr).')  ORDER BY RAND() LIMIT 20 ';
		else
			return null;
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		if(count($rs) > 0){
			foreach ($rs as $item)
				$itune_id[] = $item->id;
			$query = 'SELECT a.id as title_id , a.title as main_title, a.alias, b.des ,b.bg
			FROM #__apkipas_titles as a
			LEFT JOIN #__apkipas_resources as b ON a.product_id = b.id
			WHERE b.itune_id IN ('.implode(',', $itune_id).') AND a.id != '.$id.' GROUP BY b.itune_id ORDER BY a.id DESC LIMIT 6';
			
			$db->setQuery($query);
			return $db->loadObjectList();
		}
		
	}
}
